﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WxPayAPI;
using Yule8xCommon.Applib;
using Yule8xCommon.Db;
using Yule8xModel;
using Yule8xCommon.Typelib;
using Yule8xWechat.Applib;

namespace Yule8xWechat.Payment.WxPay
{
    public partial class AgentRegistion : System.Web.UI.Page
    {
        protected WxUserInfoResult wxUser = null;
        private string wxJsApiParam;
        protected int smscountdown;
        protected int user_id;
        protected int parent1_uid_default;
        protected void Page_Load(object sender, EventArgs e)
        {
            user_id = RequestUtil.GetInteger("user_id");
            if (RuntimeDataUtil.CheckDebugModel() && user_id > 0)
            {
                wxUser = UserModels.GetWxUserInfo(user_id);
                if (null == wxUser)
                {
                    ResponseUtil.WriteEnd("user_id无效!");
                }
            }
            else
            {
                wxUser = LoginPageBase.GetLoginInfo();
                if (null == wxUser)
                {
                    Response.Redirect(WechatUrls.GetUserInfoUrl("agentregist"), true);
                }
            }
            if (user_id < 1 && UserModels.CheckUserIsAgent(wxUser.user_id))
            {
                RedirectUtil.RedirectTimer(true, "提示", new string[] { "您已经是代理!" }, "/Agent/Index.aspx?user_id=" + user_id);
            }

            parent1_uid_default = wxUser.parent1_uid < 1 ? 1018888 : wxUser.parent1_uid;
            /*
            // 判断登录
            object loginData = Session["login"];
            if (null != loginData)
            {
                wxUser = loginData as WxUserInfoResult;
            }
            if (null == loginData || null == wxUser)
            {
                LogUtil.Instance.WriteInfo("[申请代理] 未登录");
                Response.Redirect(WechatUrls.GetUserInfoUrl("agentregist"), true);
            }*/
            // 默认顶级代理商编号(扫码进来的是100000以下，顶级代理商是10万以上)
            LogUtil.Instance.WriteInfo("[申请代理] " + JSON.stringify(wxUser));

            smscountdown = AppConf.SMSCodeTimedown;
            string action = RequestUtil.FormString("action");
            if ("submit" == action)
            {
                DoSubmit();
            }
        }
        void DoSubmit()
        {
            int parent1_uid = RequestUtil.FormInteger("parent1_uid");
            if (parent1_uid < 1)
            {
                RedirectUtil.RedirectTimer(false, "出错啦", new string[] { "推荐人ID必需填写!" });
            }
            if (parent1_uid == wxUser.user_id)
            {
                RedirectUtil.RedirectTimer(false, "出错啦", new string[] { "推荐人ID不能是自己!" });
            }
            if (parent1_uid < 100000 && !UserModels.CheckUserIsAgent(parent1_uid))
            {
                RedirectUtil.RedirectTimer(false, "出错啦", new string[] { "推荐人ID必须已经成为代理!" });
            }
            string mobile = RequestUtil.FormString("mobile", maxLen: 16);
            if (mobile.Length < 11)
            {
                RedirectUtil.RedirectTimer(false, "出错啦", new string[] { "手机号码无效!" });
            }
            string yzm = RequestUtil.FormString("yzm", maxLen: 4);
            string realname = RequestUtil.FormString("realname", maxLen: 16);
            if (string.IsNullOrEmpty(realname))
            {
                RedirectUtil.RedirectTimer(false, "出错啦", new string[] { "真实姓名无效!" });
            }
            if (string.IsNullOrEmpty(yzm) || !UserCaptchaModels.CheckCaptchaCode(wxUser.user_id, "agentregistconfirm", yzm))
            {
                RedirectUtil.RedirectTimer(false, "出错啦", new string[] { "短信验证码已失效!" });
            }
            string outTradeNo = WxPayApi.GenerateOutTradeNo();
            decimal agent_regist_amount = AppConf.AgentRegistCardAmount; // 注册成为代理付款金额
            string attach = string.Format("agentregist:{0},{1}", wxUser.user_id, wxUser.unionid);
            string msg;
            bool result = UserModels.UserRegistAgentSubmit(wxUser.user_id, agent_regist_amount, outTradeNo, mobile, realname, parent1_uid, attach, out msg);
            if (result)
            {
                // 微信支付
                WxJsPay(outTradeNo, agent_regist_amount, attach);
            }
            else
            {
                RedirectUtil.RedirectTimer(false, "出错啦", new string[] { msg });
            }
            Response.End();
        }
        // 微信公众号支付
        void WxJsPay(string outTradeNo, decimal amount, string attach)
        {
            bool onecentpay = RuntimeDataUtil.CheckOnecentPay(wxUser.user_id); // 一分钱支付
            string openid = wxUser.openid;
            string total_fee = onecentpay ? "1" : (amount * 100).ToString(); // 分
            if (onecentpay)
            {
                LogUtil.Instance.WriteError(string.Format("[注册成为代理] user_id={0}, total_fee={1}, amount={2} 使用OCP支付模式", wxUser.user_id, total_fee, amount), null);
            }

            //若传递了相关参数，则调统一下单接口，获得后续相关接口的入口参数
            JsApiPay jsApiPay = new JsApiPay(this);
            jsApiPay.openid = openid;
            jsApiPay.total_fee = (int)decimal.Parse(total_fee);

            //JSAPI支付预处理
            try
            {
                WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(outTradeNo, attach, "注册成为代理");
                wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数

                LogUtil.Instance.WriteInfo("[购买钻石] wxJsApiParam: " + wxJsApiParam);
                LogUtil.Instance.WriteInfo("[注册成为代理] 订单详情: " + unifiedOrderResult.ToPrintStr());

                string str = "<script>function jsApiCall() { WeixinJSBridge.invoke( 'getBrandWCPayRequest'," + wxJsApiParam + ", function (res) { WeixinJSBridge.log(res.err_msg); if(res.err_msg=='get_brand_wcpay_request:ok'){window.location.replace('../../Agent/Index.aspx');} } ); } function callpay() { if (typeof WeixinJSBridge == \"undefined\") { if (document.addEventListener) { document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); } else if (document.attachEvent) { document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } } else { jsApiCall(); } } callpay();</script>";
                LogUtil.Instance.WriteInfo("[注册成为代理] 发起微信支付脚本：" + str);
                Response.Write(str);
            }
            catch
            {
                Response.Write("<span style='color:#FF0000;font-size:20px'>" + "下单失败，请返回重试" + "</span>");
            }
        }
    }
}